package ack.service;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

@Service
public class AckPublishServiceImpl {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void setMSG(){
        CorrelationData correlationData = new CorrelationData();
        String uuid = UUID.randomUUID().toString();
        System.out.println("Thread.currentThread().getId() = " + Thread.currentThread().getId());
        System.out.println("uuid = " + uuid);
        //如果你不设置id，发布确认回调的第一个参数还是有id的，是broker自动生成的
        correlationData.setId(uuid);
        Object data="ggggggg";
        rabbitTemplate.convertAndSend("ackqueue",data,correlationData);

        //回调确认是异步的，与发送数据的线程不是同一个
        rabbitTemplate.setConfirmCallback((cdata,ack,cause)->{
            System.out.println("Thread.currentThread().getId() = " + Thread.currentThread().getId());
            if (ack) {
                System.out.println(cdata.getId()+"发送成功");

            }else {
                System.out.println("消息发送失败-- 原因："+cause);
            }
        });
    }





    public void getMSG(){
        CorrelationData correlationData = new CorrelationData();
        String uuid = UUID.randomUUID().toString();
        correlationData.setId(uuid);

        rabbitTemplate.setReturnsCallback((returnedMessage)->{
            System.out.println("returnedMessage.getReplyCode() = " + returnedMessage.getReplyCode());
            System.out.println("returnedMessage.getReplyText() = " + returnedMessage.getReplyText());
            System.out.println("returnedMessage.getRoutingKey() = " + returnedMessage.getRoutingKey());
            try {
                System.out.println("new String(returnedMessage.getMessage().getBody(),\"UTF-8\") = " + new String(returnedMessage.getMessage().getBody(), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        });

        Object data="return callback";
        //发给默认的交换机或者指定的交换机，只要没有进入到队列，return回调都会执行
        //要在配置文件中进行配置

        rabbitTemplate.convertAndSend("adsds",data,correlationData);

    }
}
